package com.example.leixin.helloworld.net;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.leixin.helloworld.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HttpActivity extends AppCompatActivity implements View.OnClickListener {

    TextView responseText;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http);

        Button button_send_request = (Button) findViewById(R.id.button_send_request);
        button_send_request.setOnClickListener(this);

        Button button_okhttp_send_request = (Button) findViewById(R.id.button_okhttp_send_request);
        button_okhttp_send_request.setOnClickListener(this);

        Button button_clear = (Button) findViewById(R.id.button_clear);
        button_clear.setOnClickListener(this);

        Button button_json = (Button) findViewById(R.id.button_json);
        button_json.setOnClickListener(this);

        Button button_gson = (Button) findViewById(R.id.button_gson);
        button_gson.setOnClickListener(this);

        responseText = (TextView) findViewById(R.id.response_text);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_send_request:
                responseText.setText("");
                sendRequestWithHttpURLConnection();
                break;
            case R.id.button_okhttp_send_request:
                responseText.setText("");
                sendRequestWithOkHttp();
                break;
            case R.id.button_json:
                responseText.setText("");
                sendRequestWithJson();
                break;
            case R.id.button_gson:
                responseText.setText("");
                sendRequestWithGson();
                break;
            case R.id.button_clear:
                responseText.setText("");
                break;
        }
    }

    private void sendRequestWithGson() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url("http://jsonplaceholder.typicode.com/todos").build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    parseJSONWithGson(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void parseJSONWithGson(String responseData) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("Todos: \n");

        Gson gson = new Gson();
        List<Todo> todoList = gson.fromJson(responseData, new TypeToken<List<Todo>>() {
        }.getType());
        for (Todo todo : todoList) {
            String userId = todo.getUserId();
            int id = todo.getId();
            String title = todo.getTitle();
            boolean completed = todo.getCompleted();
            stringBuilder.append(String.format("userId:%s id:%d title:%s completed:%b \n", userId, id, title, completed));
        }
        showResponse(stringBuilder.toString());
    }

    private void sendRequestWithJson() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url("http://jsonplaceholder.typicode.com/todos").build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    parseJSONWithJSOnObject(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void parseJSONWithJSOnObject(String responseData) {
        try {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("Todos: \n");
            JSONArray jsonArray = new JSONArray(responseData);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String userId = jsonObject.getString("id");
                int id = jsonObject.getInt("id");
                String title = jsonObject.getString("title");
                boolean completed = jsonObject.getBoolean("completed");
                stringBuilder.append(String.format("userId:%s id:%d title:%s completed:%b \n", userId, id, title, completed));
            }
            showResponse(stringBuilder.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url("http://www.sina.com").build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void sendRequestWithHttpURLConnection() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL("https://www.baidu.com");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);

                    /*
                    // POST方式提交数据
                    connection.setRequestMethod("POST");]
                    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
                    outputStream.writeBytes("username=admin&password=123456");
                    */

                    InputStream in = connection.getInputStream();
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    showResponse(response.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                responseText.setText(response);
            }
        });
    }
}